package com.csun.nusing.ui.activity;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.csun.nusing.R;
import com.csun.nusing.bean.UrlBean;
import com.csun.nusing.bean.jsonbean.BaseJsonBean;
import com.csun.nusing.presenter.CommonPresenter;
import com.csun.nusing.presenter.inter.IBase;
import com.csun.nusing.ui.BaseActivity;
import com.csun.nusing.util.SPUtils;
import com.csun.nusing.util.ToastUtil;
import com.csun.ttfutil.TTFSdk;
import com.google.gson.Gson;
import com.home.administrator.okhttplibrary.IOkTaskCallback;
import com.home.administrator.okhttplibrary.OkHttpTask;
import com.home.administrator.okhttplibrary.OkHttpTask.OkHttpTaskBuidler.OkType;
import com.linktop.whealthService.HealthApi;
import com.linktop.whealthService.HealthApi.BleCallBack;
import com.linktop.whealthService.HealthApi.EcgCallBack;
import com.linktop.whealthService.HealthApi.HealthApiCallBack;
import com.linktop.whealthService.OnBLEService;
import com.linktop.whealthService.task.BT_task;
import com.linktop.whealthService.task.Bp_task;
import com.linktop.whealthService.task.Bs_task;
import com.linktop.whealthService.task.Ox_task;
import com.linktop.whealthService.task.battery_task;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 温度测试界面 ClassName: TemperatureMeasureActivity
 * 
 * @Description: 温度测试
 * @author fzq
 * @date 2017-10-10
 */
public class TemperatureMeasureActivity extends BaseActivity<CommonPresenter>
		implements IBase {

	private TextView temperature_messure_test_tv;
	private TextView temperature_messure_test_temp_tv;
	private HealthApi mHealthApi;
	private final boolean START = true;
	private final boolean STOP = false;
	private boolean bt_button_state = true;
	private Timer batteryQueryTimer;
	private String olderId;
	private String authorization;
	private RelativeLayout navrl;
	private boolean isFamily;
	private ProgressBar progressbar;

	@Override
	public int getContentViewId() {
		return R.layout.activity_temperature_measure;
	}

	@Override
	public void initSubViews(View view) {
		super.initSubViews(view);
		initView();
	}

	@Override
	public void initData() {
		super.initData();
		olderId = getIntent().getStringExtra("olderId");
		navrl = findViewById(R.id.nav_rl);
		isFamily = getIntent().getBooleanExtra("isFamily", false);
		if (isFamily) {
			navrl.setBackgroundResource(R.drawable.main_whiteyello_color_shape);
		}
		initHealth();
	}

	/**
	 * @Description: 初始化测量
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-10
	 */
	private void initHealth() {
		mHealthApi = new HealthApi();
		mHealthApi.init(getApplicationContext(), new healthapicallback(),
				mbpHandler, mbtHandler, moxHandler, mbsHandler,
				new ecgcallback());

		mHealthApi.setBleCallBack(new blecallback());

		Log.e("version", HealthApi.getVersion());
	}

	/**
	 * @Description: find控件
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-10
	 */
	private void initView() {
		temperature_messure_test_tv = findViewById(R.id.temperature_messure_test_tv);
		temperature_messure_test_temp_tv = findViewById(R.id.temperature_messure_test_temp_tv);
		progressbar = findViewById(R.id.temperature_measure_progressbar);
		temperature_messure_test_tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startMessure();
			}
		});
	}

	/**
	 * 测量温度
	 * 
	 * @Description: 测量温度
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-10
	 */
	protected void startMessure() {
		if (bt_button_state == START) {
			if (BluetoothAdapter.getDefaultAdapter().isEnabled()) {
				mHealthApi.startBT();
				progressbar.setVisibility(View.VISIBLE);
				bt_button_state = STOP;
				temperature_messure_test_temp_tv.setText("--℃");
				temperature_messure_test_tv.setText(R.string.stop);
			} else {
				finish();
			}
		} else {
			bt_button_state = START;
			progressbar.setVisibility(View.GONE);
			temperature_messure_test_tv.setText(R.string.measure);
		}
	}

	/**
	 * 上传温度
	 * 
	 * @Description: TODO
	 * @param @param format
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-31
	 */
	protected void sendDate(String format) {
		authorization = (String) SPUtils.get(this, "authorization", "");
		HashMap<String, String> param = new HashMap<String, String>();
		param.put("oldmanId", olderId);
		param.put("temperature", format + "");
		OkHttpTask.newInstance(this).addHeader("authorization", authorization)
				.post(param, OkType.form).enqueue(new IOkTaskCallback() {
					@Override
					public void onSuccess(String result) {
						Gson gson = new Gson();
						if (result != null) {
							BaseJsonBean baseJsonBean = gson.fromJson(result,
									BaseJsonBean.class);
							ToastUtil.showMessage(getApplicationContext(),
									baseJsonBean.getMessage());
						}
					}
				}).start(UrlBean.FOLLOWTEMPERATUREUPURL);
	}

	private class healthapicallback implements HealthApiCallBack {

		@Override
		public void healthCallBack(int type, Object data) {
			// TODO Auto-generated method stub
			switch (type) {
			case HealthApi.BIND_FINISHED:
				break;
			case HealthApi.BATTERY:
				setBatteryUi((byte[]) data);
				break;
			case HealthApi.UPDATA_CON_INTERVAL_FAIL_ACTION:
				break;
			case HealthApi.QUERY_ECG_MODULE_EXIST:
				byte modual = (Byte) data;
				break;
			case HealthApi.QUERY_BS_MODULE_EXIST:
				byte modual1 = (Byte) data;
				break;
			case HealthApi.INTENT_DEVICE_VERSION_SOFE:
				String sofe = (String) data;
				break;
			case HealthApi.INTENT_DEVICE_VERSION_HARD:
				String hard = (String) data;
				break;
			}
		}
	}

	private class blecallback implements BleCallBack {

		@Override
		public void bleCallBack(int type, Object data) {
			if (type == HealthApi.BLE_STATUS) {
				setBleUiState((Integer) data);
			}
		}
	}

	private void modual_init() {
		mHealthApi.ecgQuery();
		mHealthApi.bsQuery();
		mHealthApi.batteryQuery();

		if (batteryQueryTimer == null)
			batteryQueryTimer = new Timer();
		batteryQueryTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				mHealthApi.batteryQuery();
			}
		}, 300000, 300000);
	}

	private void setBleUiState(int mState) {

		switch (mState) {
		case OnBLEService.BLE_CONNECTED:
			break;
		case OnBLEService.BLE_DISCONNECTED:
			break;
		case OnBLEService.BLE_NOTIFICATION_ENABLED:
			modual_init();
			break;
		case OnBLEService.BLE_NOTIFICATION_NOTENABLED:
			break;
		default:
			break;
		}

	}

	private void setBatteryUi(byte[] battery) {
		switch (battery[0]) {
		case battery_task.BATTERY_QUERY:
			break;
		case battery_task.BATTERY_CHARING:
			break;
		case battery_task.BATTERY_FULL:
		default:
			break;
		}
	}

	private class ecgcallback implements EcgCallBack {

		@Override
		public void onReceive(int[] data) {
			// TODO Auto-generated method stub
			switch (data[0]) {
			case HealthApi.ECG_DATA:
				// tv.append("SmoothedRaw: " + data + "\n");
				break;
			case HealthApi.ECG_HEARTRATE:
				final int avg_hr = data[1];
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
					}
				});
				break;
			case HealthApi.ECG_RRMAX:
				final int rrmaxint = data[1];
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
					}
				});
				break;
			case HealthApi.ECG_RRMIN:
				final int rrminint = data[1];
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
					}
				});
				break;
			case HealthApi.ECG_HRV:
				final int hRV = data[1];
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
					}
				});
				break;
			case HealthApi.ECG_MOOD:
				final int mood = data[1];
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
					}
				});
				break;
			case HealthApi.ECG_BR:
				// tv.append("Robust HR: " + data + "\n");
				Log.i("Robust HR ", data + "\n" + "");
				final int br = data[1];
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
					}
				});
				break;
			case HealthApi.ECG_END:
				break;
			default:
				break;
			}
		}
	}

	/**
	 * 温度测量
	 */
	private Handler mbtHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case BT_task.BT_RESULT:
				double result = msg.getData().getDouble("BodyTempResult");
				temperature_messure_test_temp_tv.setText(String.format("%.1f",
						result) + "℃");
				TTFSdk.speak(mSpeechSynthesizer,getString(R.string.health_temperature) + String.format("%.1f", result)
						+ getString(R.string.temparture));
				bt_button_state = START;
				temperature_messure_test_tv.setText(R.string.measure);
				progressbar.setVisibility(View.GONE);
				sendDate(String.format("%.1f", result));
				break;
			default:
				break;
			}
		}
	};

	@SuppressLint("HandlerLeak")
	private Handler moxHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Ox_task.OXYGEN_TEST_FINISH:
				double[] data = msg.getData().getDoubleArray("oxyResult");
				if (data != null) {
				}
				break;
			case Ox_task.AXIS_DATA:
				int red_value = msg.getData().getInt("oxDataRed");

				break;

			case Ox_task.OX_CMD_TIMEOUT:
				int ox_cmd_type = msg.getData().getInt("ox_cmd_type");
				break;
			default:
				break;
			}
		}
	};

	@SuppressLint("HandlerLeak")
	private Handler mbpHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Bp_task.BP_RESULT:
				int systolic = msg.arg1;
				int diastolic = msg.arg2;
				int heartRate = msg.getData().getInt("heartRate");
				break;
			case Bp_task.LOUQI:
				break;

			default:
				break;
			}
		}
	};
	@SuppressLint("HandlerLeak")
	private Handler mbsHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Bs_task.BS_PAPER_STATUS:
				int init_paper = msg.getData().getByte("initpaperStatus");
				break;
			case Bs_task.BS_PAPER_IS_READY:
				break;
			case Bs_task.BS_PAPER_CHECK_TIMEOUT:
				break;
			case Bs_task.BS_BLOOD_CHECK_TIMEOUT:
				break;
			case Bs_task.BS_TESTING_PAPER_OUT:
				break;
			case Bs_task.BS_RESULT:
				break;
			case Bs_task.BS_PAPER_IS_USED:
				break;
			case Bs_task.BS_GET_VER_FAIL:
				break;
			case Bs_task.BS_BLOOD_IN_DETECTED:
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mHealthApi != null)
			mHealthApi.recover();
		if (batteryQueryTimer != null)
			batteryQueryTimer.cancel();
		batteryQueryTimer = null;
	}

}
